// @ts-nocheck

// 表格对齐方式
const ALIGN = {
  LEFT: 'margin-left:0;margin-right: auto;',
  CENTER: 'margin-left:auto;margin-right: auto;',
  RIGHT: 'margin-left:auto;margin-right: 0;'
}

export function updateColumns(node, colgroup, table, cellMinWidth, overrideCol, overrideValue) {
  let totalWidth = 0
  let fixedWidth = true
  let nextDOM = colgroup.firstChild
  const row = node.firstChild

  for (let i = 0, col = 0; i < row.childCount; i += 1) {
    const { colspan, colwidth } = row.child(i).attrs

    for (let j = 0; j < colspan; j += 1, col += 1) {
      const hasWidth = overrideCol === col ? overrideValue : colwidth && colwidth[j]
      const cssWidth = hasWidth ? `${hasWidth}px` : ''

      totalWidth += hasWidth || cellMinWidth

      if (!hasWidth) {
        fixedWidth = false
      }
      if (!nextDOM) {
        colgroup.appendChild(document.createElement('col')).style.width = cssWidth
      } else {
        if (nextDOM.style.width !== cssWidth) {
          nextDOM.style.width = cssWidth
        }

        nextDOM = nextDOM.nextSibling
      }
    }
  }

  while (nextDOM) {
    const after = nextDOM.nextSibling

    nextDOM.parentNode.removeChild(nextDOM)
    nextDOM = after
  }
  if (fixedWidth) {
    table.style.width = `${totalWidth}px`
    table.style.minWidth = ''
  } else {
    table.style.width = ''
    table.style.minWidth = `${totalWidth}px`
  }
}

export class TableView {
  constructor(node, cellMinWidth) {
    this.node = node
    this.cellMinWidth = cellMinWidth
    const container = document.createElement('div')
    container.style = 'max-width: 100%;margin: 8px 0;'
    this.dom = container
    const tableDom = document.createElement('table')
    this.table = this.dom.appendChild(tableDom)
    this.colgroup = this.table.appendChild(document.createElement('colgroup'))
    updateColumns(node, this.colgroup, this.table, cellMinWidth)
    this.contentDOM = this.table.appendChild(document.createElement('tbody'))
  }

  update(node) {
    if (node.type !== this.node.type) {
      return false
    }
    this.node = node
    let style = node.attrs['style'] + ';'
    for (const attr in node.attrs) {
      this.table.setAttribute(attr, node.attrs[attr])
      if (attr === 'data-align') {
        let alignStyle = ALIGN[node.attrs[attr].toUpperCase()]
        style += alignStyle
      }
    }
    this.table.setAttribute('style', style)
    updateColumns(node, this.colgroup, this.table, this.cellMinWidth)

    return true
  }

  ignoreMutation(mutation) {
    return (
      mutation.type === 'attributes'
      && (mutation.target === this.table || this.colgroup.contains(mutation.target))
    )
  }
}
